package editor;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
// This is the main function for exporting PDF files
public class TurnintoPDF {
    public void PDFItem(String pathname, String filename, File file) throws IOException {
        FileInputStream in = new FileInputStream(file);
        byte[] byt = new byte[1024];
        int len = in.read(byt);
        String text = new String(byt, 0, len);
        String[] text1 = text.split("\n");
       // Compatible processing for exporting large files to PDF format
        PDDocument document = new PDDocument();
        for (int i =0;i<=text1.length/50;i++){
            PDPage my_page = new PDPage();
            document.addPage(my_page);
        }
        document.save(pathname+".pdf");
        File file1 = new File(pathname+".pdf");
        document = PDDocument.load(file1);
//        //Retrieving the pages of the document

        for (int i =0;i<=text1.length/50;i++){
            System.out.println(i);
            String[] strings = new String[51];
            for(int j=0;j<51;j++){
                strings[j] = " ";
            }
            int i1 = 0;
            System.out.println(text1.length);
            for (int index=i*50+i;index<=i*50+i+50;index++){
                System.out.println("**" + i1 + "**" + index);
                if (index >= text1.length)
                    break;
                strings[i1] = text1[index];
                i1++;
            }
            PDPage page = document.getPage(i);
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
//        //Begin the Content stream
            contentStream.beginText();
//        //Setting the font to the Content stream
            contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
//        //Setting the position for the line
            contentStream.setLeading(14.5f);
            contentStream.newLineAtOffset(25, 750);

            for (String s : strings) {
                System.out.println(s);
                contentStream.showText(s);
                contentStream.newLine();
            }
            contentStream.endText();
            contentStream.close();
        }

        document.save(new File(pathname+".pdf"));
        //Please pay attention to the naming format of the new PDF file
        document.close();

    }
}
